﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DTO;

namespace DAO
{

	public class VendorDAO:IData
 	{
		public VendorDAO(String myconnecString) : base(myconnecString) { }

		public  int OnSubmit(Vendor item, int t) {
			 return connec.ExecuteNonQuery("sp_Vendor", CommandType.StoredProcedure,new SqlParameter("@flag", t),
				 new SqlParameter("@" + Vendor.c_id, item.id), new SqlParameter("@" + Vendor.c_name, item.name),
				 new SqlParameter("@" + Vendor.c_address, item.address), new SqlParameter("@" + Vendor.c_email, item.email),
				 new SqlParameter("@" + Vendor.c_Logo, item.Logo), new SqlParameter("@" + Vendor.c_Website, item.Website)); 
		}

		public  Vendor GetItem(IDataReader dr)
		{
			Vendor obj = new Vendor();
			obj.id = Convert.ToInt32(dr[Vendor.c_id]);
			obj.name = Convert.ToString(dr[Vendor.c_name]);
			obj.address = Convert.ToString(dr[Vendor.c_address]);
			obj.email = Convert.ToString(dr[Vendor.c_email]);
			obj.Logo = Convert.ToString(dr[Vendor.c_Logo]);
			obj.Website = Convert.ToString(dr[Vendor.c_Website]);
			return obj;
		}

        private List<Vendor> GetAll(String strSQL, CommandType commandtype)
        {
            List<Vendor> list = new List<Vendor>();
            SqlConnection connection = connec.Connection;
            SqlCommand command = new SqlCommand();
            command.CommandType = commandtype;
            command.CommandText = strSQL;
            command.Connection = connection;
            connection.Open();
            SqlDataReader reader;
            using (reader = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    list.Insert(0, GetItem(reader));
                }
                reader.Close();
            }
            connection.Close();
            return list;
        }
		public  List<Vendor> GetAll()
		{
			return GetAll("select * from " + Vendor.b_Vendor, CommandType.Text);
		}

		public  Vendor GetItemById(object id)
		{
			 return this.GetAll().FirstOrDefault(x => x.id == (long)id);
		}

	}

 }
